<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="isEditing = !isEditing">
            {{ isEditing ? '取消编辑' : '编辑资料' }}
          </el-button>
        </div>
      </template>
      
      <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="100px" :disabled="!isEditing">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="avatar-upload">
              <el-avatar :size="120" :src="userInfo.avatar || defaultAvatar" />
              <div class="upload-btn" v-if="isEditing">
                <el-upload
                  action="#"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAvatarChange"
                >
                  <el-button type="primary">更换头像</el-button>
                </el-upload>
              </div>
            </div>
          </el-col>
          <el-col :span="16">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userInfo.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userInfo.nickname" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userInfo.phone" />
            </el-form-item>
            <el-form-item label="用户类型">
              <el-input v-model="userInfo.userTypeText" disabled />
            </el-form-item>
            <el-form-item label="注册时间">
              <el-input v-model="userInfo.createTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="center">其他信息</el-divider>
        
        <el-form-item label="个人简介" prop="introduction">
          <el-input v-model="userInfo.introduction" type="textarea" :rows="4" />
        </el-form-item>
        
        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="isEditing = false">取消</el-button>
        </el-form-item>
        
        <!-- 开发调试信息 -->
        <el-divider content-position="center">开发调试信息</el-divider>
        <div class="debug-info">
          <pre>{{ JSON.stringify(userInfo, null, 2) }}</pre>
        </div>
      </el-form>
    </el-card>
    
    <el-card class="profile-card security-card">
      <template #header>
        <div class="card-header">
          <span>安全设置</span>
        </div>
      </template>
      
      <el-form label-width="100px">
        <el-form-item label="账号密码">
          <span>已设置</span>
          <el-button link type="primary" @click="showUpdatePwdDialog = true">修改</el-button>
        </el-form-item>
        
        <el-form-item label="绑定手机">
          <span>{{ userInfo.phone || '未绑定' }}</span>
          <el-button link type="primary" @click="showBindPhoneDialog = true">{{ userInfo.phone ? '更换' : '绑定' }}</el-button>
        </el-form-item>
        
        <el-form-item label="绑定邮箱">
          <span>{{ userInfo.email || '未绑定' }}</span>
          <el-button link type="primary" @click="showBindEmailDialog = true">{{ userInfo.email ? '更换' : '绑定' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
  <!-- 修改密码弹窗 -->
  <el-dialog
    v-model="showUpdatePwdDialog"
    title="修改密码"
    width="500px"
  >
    <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="120px">
      <el-form-item label="当前密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showUpdatePwdDialog = false">取消</el-button>
        <el-button type="primary" @click="updatePassword">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUser, updateUser, changePassword } from '@/api/user'
import { useRouter } from 'vue-router'

// 默认头像
const defaultAvatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'

// 是否编辑模式
const isEditing = ref(false)

// 弹窗控制
const showUpdatePwdDialog = ref(false)
const showBindPhoneDialog = ref(false)
const showBindEmailDialog = ref(false)

// 用户信息
const userInfo = ref({
  userId: null,
  username: '',
  nickname: '',
  avatar: '',
  email: '',
  phone: '',
  userType: '',
  userTypeText: '',
  createTime: '',
  introduction: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (passwordForm.value.confirmPassword !== '') {
      if (passwordForm.value.confirmPassword !== value) {
        callback(new Error('两次输入密码不一致!'))
      }
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// 获取用户信息
function getUserInfo() {
  try {
    const userFromStorage = localStorage.getItem('userInfo')
    if (userFromStorage) {
      const parsedUser = JSON.parse(userFromStorage)
      console.log('从localStorage获取的用户信息:', parsedUser)
      
      userInfo.value = {
        ...userInfo.value,
        ...parsedUser
      }
      
      // 如果userTypeText不存在，则根据userType生成
      if (!userInfo.value.userTypeText) {
        switch (userInfo.value.userType) {
          case '01':
            userInfo.value.userTypeText = '管理员'
            break
          case '02':
            userInfo.value.userTypeText = '经销商'
            break
          case '03':
            userInfo.value.userTypeText = '普通用户'
            break
          default:
            userInfo.value.userTypeText = '未知'
        }
      }
      
      // 确保显示一些必要的默认值
      userInfo.value.avatar = userInfo.value.avatar || defaultAvatar
      userInfo.value.nickname = userInfo.value.nickname || userInfo.value.username || '未设置昵称'
      
      console.log('处理后的用户信息:', userInfo.value)
    } else {
      console.error('localStorage中未找到用户信息')
      ElMessage.error('未找到用户信息，请重新登录')
      router.push('/login')
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 提交表单
function handleSubmit() {
  try {
    // 更新本地存储的用户信息
    const updatedUserInfo = {
      ...userInfo.value,
      userTypeText: undefined // 不保存用户类型文本，因为它是由 userType 动态生成的
    }
    
    console.log('保存更新后的用户信息:', updatedUserInfo)
    localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
    
    // 如果需要，这里可以调用后端API更新用户信息
    // const response = await updateUser(updatedUserInfo);
    
    ElMessage.success('用户信息更新成功')
    isEditing.value = false
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  }
}

// 更新密码
function updatePassword() {
  try {
    // 验证新密码与确认密码是否一致
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      ElMessage.error('新密码与确认密码不一致')
      return
    }
    
    console.log('尝试更新密码:', {
      oldPassword: '******',
      newPassword: '******'
    })
    
    // 这里应该调用后端API更新密码
    // const response = await updatePassword({
    //   userId: userInfo.value.userId,
    //   oldPassword: passwordForm.value.oldPassword,
    //   newPassword: passwordForm.value.newPassword
    // });
    
    ElMessage.success('密码修改成功')
    showUpdatePwdDialog.value = false
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  }
}

// 处理头像变更
function handleAvatarChange(file) {
  try {
    // 这里应该上传文件到服务器
    // 简化示例，仅使用本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      userInfo.value.avatar = e.target.result
      // 更新本地存储的头像
      const updatedUserInfo = {
        ...userInfo.value,
        userTypeText: undefined
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
    }
    reader.readAsDataURL(file.raw)
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  getUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  
  .profile-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .avatar-upload {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;
      
      .upload-btn {
        margin-top: 10px;
      }
    }
  }
  
  .security-card {
    margin-top: 20px;
  }
  
  .debug-info {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 12px;
    max-height: 200px;
    overflow: auto;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
    }
  }
}
</style> 